package com.blog.dao.impl;


import com.blog.dao.ArticlesDao;

import com.blog.dto.FavoriteDTO;
import com.blog.pojo.Articles;
import com.blog.pojo.Favorite;
import com.blog.pojo.Start;
import com.blog.service.ArticleService;
import com.blog.service.impl.ArticleServiceImpl;
import com.blog.util.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ArticlesDaoImpl implements ArticlesDao {
    private QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
    @Override
    public int addArticles(Articles articles) {
        String sql = "insert into articles(title,content,status,userId,createdAt,updatedAt) values(?,?,?,?,?,?)";
        Object[] params = {articles.getTitle(),articles.getContent(),articles.getStatus(),articles.getUserId(),articles.getCreatedAt(),articles.getUpdatedAt()};

        try {
          int add = queryRunner.update(sql, params);
            return add;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public int deleteArticles(int id) {
        String sql = "delete from articles where id = ?";
        Object[] params = {id};
        int  delete =0;
        try {
            delete = queryRunner.update(sql, params);

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return delete;
    }

    @Override
    public int updateArticles(Articles articles) {
        String sql = "update articles set title = ?, content = ? where id = ?;";
        Object[] params = {articles.getTitle(), articles.getContent(), articles.getId()};

        try {
            int update =  queryRunner.update(sql, params);
            return update;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<Articles> findByAuthor(String  author) {
        String sql = "select * from articles where author_id= ?";
        Object[] params = {author};
        List<Articles>   query=null;
        try {
             queryRunner.query(sql,params, new BeanListHandler< Articles>(Articles.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return query;

    }

    @Override
    public Articles findByTitle(String title) {
        String sql = "select * from articles where title = ?";
        Object[] params = {title};
        Articles query = null;
        try {
            query = queryRunner.query(sql, new BeanHandler<Articles>(Articles.class), params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return query;
    }

    @Override
    public List<Articles> findAll() {
        String sql = "select * from articles";
        try {
            List<Articles> query = queryRunner.query(sql, new BeanListHandler<Articles>(Articles.class));
            return query;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public Articles findById(int id) {
        String sql = "select * from articles where id = ?";
        Object[] params = {id};
        try {
           Articles articles= queryRunner.query(sql, new BeanHandler<Articles>(Articles.class),params);
            return articles ;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<Articles> finbByUserId(int userId) {
        String sql="SELECT * FROM articles WHERE userId=? ";
        Object[] params = {userId};
        try {
            List<Articles> articles = queryRunner.query(sql, new BeanListHandler<Articles>(Articles.class), params);
            return articles;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }

    @Override
    public List<Articles> findByUserIdAndStatus(int userId, byte status) {
        String sql="SELECT * FROM articles WHERE userId=? AND status=0 ORDER BY createdAt DESC";
        Object[] params = {userId};
        try {
      List<Articles> articlesList=queryRunner.query(sql, new BeanListHandler<Articles>(Articles.class), params);
            return articlesList;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public int deleteStart(int articleId, int userId) {
        String sql = "DELETE FROM start WHERE articleId = ? AND userId = ?";
        Object[] params = {articleId,userId};

        try {
            int  delete = queryRunner.update(sql, params);
            return delete;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }

    @Override
    public int addStart(Start start) {
        String sql="INSERT INTO start(articleId,userId,start,createTime) VALUES(?,?,?,NOW())";
        Object[] params = {start.getArticleId(),start.getUserId(),start.getStart()};
        try {
            int add = queryRunner.update(sql, params);
            return add ;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public long findStartCount(int articleId , Byte start) {
        String sql = "SELECT COUNT(*) FROM start WHERE articleId = ? AND start = 1";
        Object[] params = {articleId};

            long count = 0;
            try {
                count = queryRunner.query(sql, new ScalarHandler<>(), params);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
            return count;
    }

    @Override
    public boolean findStart(int articleId, int userId, Byte start) {
        String sql = "SELECT count(*) from start where articleId=? AND start=1 AND userId=?";
        Object[] params = {articleId,userId};
        try {
           Long count = queryRunner.query(sql, new ScalarHandler<>() , params);
           return count > 0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }





    @Override
    public int addFavorite(Favorite favorite) {
        String sql="INSERT INTO favorite(articleId,userId,favorite,createTime) VALUES(?,?,?,NOW())";
        Object[] params = {favorite.getArticleId(),favorite.getUserId(),favorite.getFavorite()};

        try {
          int   add = queryRunner.update(sql, params);
            return add;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }


    }

    @Override
    public int deleteFavorite(int articleId, int userId) {
        String sql = "DELETE FROM favorite WHERE articleId = ? AND userId = ?";
        Object[] params = {articleId,userId};

        try {
            int  delete = queryRunner.update(sql, params);
            return delete;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public long findFavoriteCount(int articleId) {
        String sql = " SELECT COUNT(*) FROM favorite WHERE articleId = ? AND favorite = 1";
        Object[] params = {articleId};
        long count = 0;

        try {
            count = queryRunner.query(sql, new ScalarHandler<>(),params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return count;


    }

    @Override
    public boolean findFavorite(int articleId, int userId, Byte favorite) {
        String sql = "SELECT count(*) from favorite where articleId=? AND favorite=1 AND userId=?";
        Object[] params={articleId,userId};
        try {
           Long count= queryRunner.query(sql,new ScalarHandler<>(),params);
            return count>0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public int updateStartCount(int articleId, long startCount) {
        String sql="update articles set startCount=? where id=?";
        Object[] params={startCount,articleId};
        try {
            int update = queryRunner.update(sql, params);
            return update;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public int updateFavoriteCount(int articleId, long favoriteCount) {
        String sql="update articles set favoriteCount=? where id=?";
        Object[] params={favoriteCount,articleId};
        try {
            int update = queryRunner.update(sql, params);
            return update;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public boolean userLiked(int articleId, int userId) {
        String sql="SELECT count(*) from start where articleId=? and userId=?";
        Object[] params={articleId,userId};
        try {
          Long count=  queryRunner.query(sql, new ScalarHandler<>(), params);
            if(count>0){
                return true;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return false;
    }

    @Override
    public boolean userFavorited(int articleId, int userId) {
        String sql="SELECT count(*) from favorite where articleId=? and userId=?";
        Object[] params={articleId,userId};
        try {
            Long count=  queryRunner.query(sql, new ScalarHandler<>(), params);
            if(count>0){
                return true;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        return false;
    }

    @Override
    public List<Favorite> findFavoriteList(int userId) {
       String sql="SELECT * from favorite where userId=?";
        Object[] params={userId};
        try {
            List<Favorite> listFavorite= queryRunner.query(sql,new BeanListHandler<Favorite>(Favorite.class),params);
            return listFavorite;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

    }

    @Override
    public List<Start> userLikedArticles(int userId, List<Integer> articleIds) {
        String idStr = articleIds.stream().map(String::valueOf).collect(Collectors.joining(","));
        String sql="SELECT id, articleId, userId from start where userid=? and articleId in ( " + idStr + " )";
        Object[] params={userId};
        try {
            List<Start> startList = queryRunner.query(sql, new BeanListHandler<Start>(Start.class), params);
            return startList;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        ArticlesDao articlesDao=new ArticlesDaoImpl();
        List<Start> articlesList = articlesDao.userLikedArticles(2, Arrays.asList(4, 5, 6, 27));
        System.out.println(articlesList);
    }
}
